package com.example.griddemo.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.griddemo.R;
import com.example.griddemo.viewmodel.Category;

import java.util.ArrayList;
import java.util.List;

public class GridCategoryAdapter extends BaseAdapter {
    private List<Category> categoryList;
    private final Context context;
    private OnItemClickListener onItemClickListener;

    public interface OnItemClickListener {
        void onItemClick(Category category);
    }

    public GridCategoryAdapter(Context context, List<Category> categoryList) {
        this.context = context; // 直接使用context，不需要getApplicationContext()
        this.categoryList = categoryList != null ? categoryList : new ArrayList<>();
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.onItemClickListener = listener;
    }

    public void updateData(List<Category> newData) {
        this.categoryList = newData != null ? newData : new ArrayList<>();
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return categoryList.size();
    }

    @Override
    public Category getItem(int position) {
        return categoryList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.category_list_item, parent, false);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        final Category category = getItem(position);
        holder.bind(category);

        // 设置点击事件
        convertView.setOnClickListener(v -> {
            if (onItemClickListener != null) {
                onItemClickListener.onItemClick(category);
            }
        });

        return convertView;
    }

    private class ViewHolder {
        private final ImageView right_category_item_img;
        private final TextView right_category_item_txt;

        ViewHolder(View itemView) {
            right_category_item_img = itemView.findViewById(R.id.right_category_item_img);
            right_category_item_txt = itemView.findViewById(R.id.right_category_item_txt);
        }

        void bind(Category category) {
            Glide.with(context)
                    .load(category.getPicUrl())
                    .centerCrop()
                    .into(right_category_item_img);

            right_category_item_txt.setText(category.getName());
        }
    }
}